package com.bwie.system.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName:
 * @Description:
 * @Author: zhuwenqiang
 * @Date: 2024/12/13
 */
@Log4j2
@Component
public class SendSmsUtils {

    @Autowired
    private SmsConfig smsConfig;

    /**
     * 发送短信
     * @param phoneNumbers  手机号
     * @param templateParam 短信内容的JSON字符串
     * @return
     */
    public SendSmsResponse sendSms(String phoneNumbers, String templateParam) {
        log.info("发送验证码，手机号：{}，参数：{}", phoneNumbers, templateParam);
        // 初始化请求客户端
        Client client = createClient();
        // 构造请求对象，请替换请求参数值
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumbers)
                .setSignName(smsConfig.getSignName())
                .setTemplateCode(smsConfig.getTemplateCode())
                .setTemplateParam(templateParam);
        // 获取响应对象
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            log.error("发送短信失败，失败的原因：{}", e.getMessage());
        }
        log.info("发送验证码完毕，手机号：{}，参数：{}", phoneNumbers, templateParam);
        return sendSmsResponse;
    }

    /**
     * 初始化短信发送客户端
     * @return
     */
    private Client createClient() {
        log.info("开始初始化短信发送客户端....");
        long s = System.currentTimeMillis();
        Config config = new Config()
                // 配置 AccessKey ID，请确保代码运行环境配置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(System.getenv(smsConfig.getAccessKeyId()))
                // 配置 AccessKey Secret，请确保代码运行环境配置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(System.getenv(smsConfig.getAccessKeySecret()));
        // 配置 Endpoint
        config.endpoint = smsConfig.getEndpoint();
        Client client = null;
        try {
            client = new Client(config);
        } catch (Exception e) {
            log.error("初始化短信发送客户端失败，失败的原因：{}", e.getMessage());
        }
        log.info("始化短信发送客户端完毕，耗时：{}毫秒", System.currentTimeMillis() - s);
        return client;
    }


}
